<template>
	<view class="container" @touchstart="handleCloseOverlay">

		<view class="unified-sticky-container" :class="{ 'is-active': isHeaderSticky }">
			<!-- 吸顶后显示的搜索栏 -->
			<view class="header-sticky" :style="topBarStyle">
				<view class="header-sticky-icon" @click="goBack()">
					<u-icon name="arrow-left" color="#000" size="20"></u-icon>
				</view>
				<view class="header-sticky-name">
					{{expertData.userName}}
				</view>
				<view class="container-information-right" v-if="expertData.relationType != 0"
					:class="{ 'followed-sticky': expertData.relationType == 2 || expertData.relationType == 4 }"
					@click.stop="onFollow(expertData.relationType)">
					<view class="container-information-right-img"
						v-show="expertData.relationType == 1 || expertData.relationType == 3">
						<image src="/static/index/LocalExpertsDetail/add.png" mode=""></image>
					</view>
					<view class="container-information-right-text">
						{{expertData.relationType == 2 || expertData.relationType == 4 ? '已关注' : '关注'}}
					</view>
				</view>
			</view>
		</view>

		<view class="container-header">
			<u-swiper :list="list1" height="220" imgMode="aspectFill" radius="0"
				indicatorActiveColor="#ffaa0c"></u-swiper>
			<view class="back-button" @click="goBack()" v-show="!isHeaderSticky">
				<u-icon name="arrow-left" color="#fff" size="20"></u-icon>
			</view>
		</view>
		<view class="container-information">
			<view class="container-information-left">
				<view class="container-information-left-img" @click="handleToPersonalHomepage(expertData.userId)">
					<image :src="expertData.avatar" mode=""></image>
				</view>
				<view class="container-information-left-content">
					<view class="container-information-left-content-top">
						<view class="container-information-left-content-top-name">
							{{expertData.userName}}
						</view>
						<view class="container-information-left-content-top-brige">
							<image src="/static/user-badge/intermediateIndigenous.png" mode=""></image>
						</view>
					</view>
					<view class="container-information-left-content-bottom">
						女 • {{ expertData.cityName}}
					</view>
				</view>
			</view>
			<view class="container-information-right" v-if="expertData.relationType != 0"
				:class="{ 'followed': expertData.relationType == 2 || expertData.relationType == 4 }"
				@click.stop="onFollow(expertData.relationType)">
				<view class="container-information-right-img"
					v-show="expertData.relationType == 1 || expertData.relationType == 3">
					<u-icon name="plus" class="icon" :plain="true" size="14" shape="circle" color="#FE4E4E"></u-icon>
				</view>
				<view class="container-information-right-text">
					{{expertData.relationType == 2 || expertData.relationType == 4 ? '已关注' : '关注'}}
				</view>
			</view>
		</view>

		<view class="about">
			<view class="about-title">
				关于我
			</view>

			<view class="about-content-wrapper">
				<view class="about-content">
					{{expertData.des}}
				</view>
			</view>

		</view>

		<view class="TalentShow">
			<view class="TalentShow-title">
				<view class="title-text">
					我的发现
				</view>
				<view class="TalentShow-img">
					<image src="@/static/index_line.png" mode="widthFix"></image>
				</view>
			</view>
		</view>
		<view class="scrollable-content">
			<view class="waterfall-section">
				<WaterfallPosts :left-list="leftList" :right-list="rightList"
					:active-long-press-post-id="activeLongPressPostId" @itemClick="navigateToPostDetail"
					@closeOverlay="handleCloseOverlay" @longPress="handleLongPress" @touchEnd="handleTouchEnd" />
				<u-loadmore :status="waterfallLoadStatus" />
			</view>
		</view>

		<richPostDetail :show="showRichPostDetail" @close="showRichPostDetail = false" :postData="currentDetail" />
	</view>
</template>

<script>
	import {
		getPosts,
		getClientFollow,
		getExpert
	} from '@/request/api.js';
	import WaterfallPosts from '@/components/index/waterfall-posts/waterfall-posts.vue';
	export default {
		components: {
			WaterfallPosts,
		},
		computed: {
			topBarStyle() {
				// #ifdef MP-WEIXIN
				if (this.$store.state.systemInfo.capsuleInfo.width > 0) {
					const paddingRight = this.$store.state.systemInfo.capsuleInfo.width + this.$store.state.systemInfo
						.capsuleRightPadding * 2;
					const paddingTop = this.$store.state.systemInfo.statusBarHeight + this.$store.state.systemInfo
						.capsuleRightPadding;


					return `padding:${paddingTop}px ${paddingRight}px 10rpx 30rpx;`;
				}
				// #endif
				// #ifdef APP-PLUS || H5
				return `padding-top: ${uni.getSystemInfoSync().statusBarHeight}px;`;
				// #endif
				return '';
			}
		},
		data() {
			return {
				list1: [
					"http://www.hacn86.cn/common/2025/10/11/1760164439851_20251011143359A001.jpg"
				],
				isContentCollapsed: true, // 控制内容是否折叠
				showMask: true, // 控制是否显示蒙层
				leftList: [],
				rightList: [],
				waterfallPage: 1,
				waterfallPageSize: 8,
				isWaterfallLoading: false,
				waterfallLoadStatus: 'loadmore',
				activeLongPressPostId: null,
				showRichPostDetail: false,
				isHeaderSticky: false,
				currentDetail: null,
				followLoading: false,
				content: '',
				// 初始化 expertData
				expertData: {
					userId: '',
					userName: '',
					avatar: '',
					cityName: '',
					des: '',
					relationType: 1
				},
				userId: null

			};
		},
		onReady() {
			this.$nextTick(() => {
				this.getLayoutPositions();
			});
		},
		onLoad(options) {
			this.expertData = {
				userId: '',
				userName: '',
				avatar: '',
				cityName: '',
				des: '',
				relationType: 1 // 添加默认值
			};
			if (options.userId) {
				this.userId = options.userId
				this.initData(options.userId)
			}
			this.setStatusBarWhite();
			this.loadPosts(true);
		},
		onReachBottom() {
			this.loadPosts(false);
		},
		onPullDownRefresh() {
			//如果打开的是详情弹框，下拉刷新不掉接口
			if (this.showRichPostDetail) {

			} else {
				this.loadPosts(true);
			}
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 500);

		},
		onPageScroll(e) {
			const scrollTop = e.scrollTop;
			const shouldBeSticky = scrollTop > 220;
			if (scrollTop > 220) {
				this.setStatusBarBlack()
			} else {
				this.setStatusBarWhite();
			}
			if (this.isHeaderSticky !== shouldBeSticky) {
				this.isHeaderSticky = shouldBeSticky;
			}
		},
		methods: {
			initData(userId) {
				getExpert(userId).then(res => {
					if (res.data.code == 200) {
						this.expertData = {
							...res.data.data
						}
						// 判断background是否有值，并转换为数组
						if (this.expertData.background && this.expertData.background !== '') {
							// 将逗号分割的字符串转换为数组
							this.list1 = this.expertData.background.split(',').map(url => url.trim()).filter(url =>
								url !== '');
						} else {
							// 如果没有背景图，使用默认图片
							this.list1 = [
								"http://www.hacn86.cn/common/2025/10/11/1760164439851_20251011143359A001.jpg"
							];
						}
					}
				})
			},
			handleToPersonalHomepage(userId) {
				uni.navigateTo({
					url: '/pages_sub/user/others/others?userId=' + userId
				})
			},
			async onFollow(relationType) {
				if (this.followLoading) return;

				this.followLoading = true;

				try {
					const res = await getClientFollow({
						userId: this.expertData.userId
					});

					if (res.data && res.data.code === 200) {
						// 使用映射表简化关系类型转换逻辑
						const relationTypeMap = {
							1: 2, // 未关注 -> 关注
							2: 1, // 关注 -> 未关注
							3: 4, // 被关注 -> 互相关注
							4: 3 // 互相关注 -> 被关注
						};

						// 使用 $set 或者重新赋值整个对象来确保响应式更新
						this.$set(this.expertData, 'relationType', relationTypeMap[relationType] || this.expertData
							.relationType);

						// 或者使用这种方式触发响应式更新
						// this.expertData = {
						//   ...this.expertData,
						//   relationType: relationTypeMap[relationType] || this.expertData.relationType
						// };

						// 显示操作成功的提示
						uni.showToast({
							title: (this.expertData.relationType == 1 || this.expertData.relationType == 3) ?
								'取消关注成功' : '关注成功',
							icon: 'none',
							duration: 1500
						});
					} else {
						// 处理业务逻辑错误
						uni.showToast({
							title: '操作失败，请重试',
							icon: 'none',
							duration: 1500
						});
						console.warn('关注操作失败:', res.data?.msg || '未知错误');
					}
				} catch (error) {
					// 处理网络或系统错误
					uni.showToast({
						title: '网络异常，请重试',
						icon: 'none',
						duration: 1500
					});
					console.error('关注请求出错:', error);
				} finally {
					this.followLoading = false;
				}
			},
			navigateToPostDetail(item) {
				this.currentDetail = item
				this.showRichPostDetail = true
			},
			goBack() {
				uni.navigateBack()
			},
			getLayoutPositions() {
				const query = uni.createSelectorQuery().in(this);
				query.select('.unified-sticky-container').boundingClientRect(data => {
					if (data) this.stickyHeaderHeight = data.height;
				}).exec();
			},
			async loadPosts(isRefresh = false) {
				if (this.isWaterfallLoading || (!isRefresh && this.waterfallLoadStatus === 'nomore')) return;
				this.isWaterfallLoading = true;
				this.waterfallLoadStatus = 'loading';
				if (isRefresh) {
					this.waterfallPage = 1;
					this.leftList = [];
					this.rightList = [];
				}
				const params = {
					userId: this.userId,
					queryType: 23,
					categoryId: 0,
					pageNum: this.waterfallPage,
					pageSize: this.waterfallPageSize,
					isNewDesc: 1
				};
				console.log('即将发送 getPosts 请求，参数为:', params);
				try {
					const res = await getPosts(params);
					if (res.data && res.data.code === 200) {
						const formattedPosts = (res.data.rows || []).map(this.formatApiData);
						this.distributePostsToColumns(formattedPosts);
						const hasMore = formattedPosts.length === this.waterfallPageSize;
						this.waterfallLoadStatus = hasMore ? 'loadmore' : 'nomore';
						if (hasMore) this.waterfallPage++;
					} else {
						this.waterfallLoadStatus = 'loadmore';
					}
				} catch (error) {
					this.waterfallLoadStatus = 'loadmore';
				} finally {
					this.isWaterfallLoading = false;
				}
			},
			handleLongPress(postId) {
				this.activeLongPressPostId = postId;
			},
			handleTouchEnd() {},
			handleCloseOverlay() {
				if (this.activeLongPressPostId !== null) {
					setTimeout(() => {
						this.activeLongPressPostId = null;
					}, 100);
				}
			},
			formatApiData(item) {
				const coverImage = (item.files && item.files.length > 0 && item.files[0].fileUrl) ? (item.files[0].fileUrl
					.startsWith('http') ? item.files[0].fileUrl : config.cdnURL + item.files[0].fileUrl) : '';
				const authorAvatar = item.avatar ? (item.avatar.startsWith('http') ? item.avatar : config.cdnURL + item
					.avatar) : '/static/demo/avatar_default.png';
				return {
					id: item.id,
					image: coverImage,
					content: item.content,
					author: {
						avatar: authorAvatar,
						name: item.nickName || '匿名用户',
						tag: Math.random() > 0.6 ? '高级土著' : ''
					},
					isLiked: item.isLiked,
					likeCount: item.likeCount,
					longPressTip: item.whisper || '尚未添加悄悄话',
					...item
				};
			},
			distributePostsToColumns(newPosts) {
				newPosts.forEach(post => {
					if (this.leftList.length <= this.rightList.length) this.leftList.push(post);
					else this.rightList.push(post);
				});
			},
			setStatusBarWhite() {
				// 设置状态栏前景色为白色
				uni.setNavigationBarColor({
					frontColor: '#ffffff',
					backgroundColor: '#000000',
					animation: {
						duration: 200,
						timingFunc: 'easeIn'
					}
				});
			},

			setStatusBarBlack() {
				// 如果需要切换回黑色
				uni.setNavigationBarColor({
					frontColor: '#000000',
					backgroundColor: '#ffffff',
					animation: {
						duration: 200,
						timingFunc: 'easeIn'
					}
				});
			},
			toggleContent() {
				this.isContentCollapsed = !this.isContentCollapsed;
			}
		}
	};
</script>

<style lang="scss" scoped>
	.container {
		height: 100%;

		.unified-sticky-container {
			width: 100%;
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			z-index: 998;
			background-color: #ffffff;
			visibility: hidden;
			opacity: 0;
			transition: opacity 0.3s ease-in-out, visibility 0.3s ease-in-out;

			&.is-active {
				visibility: visible;
				opacity: 1;
				padding-bottom: 20rpx;
				padding-top: 20rpx;
			}

			.header-sticky {
				padding: 0 30rpx;
				height: 60rpx;
				line-height: 60rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				position: relative; // 添加相对定位

				.header-sticky-icon {
					margin-top: 10rpx;
					z-index: 2; // 确保在文字上方
				}

				.header-sticky-name {
					position: absolute; // 绝对定位
					left: 50%; // 左边距50%
					transform: translateX(-50%); // 向左移动自身宽度的一半
					font-weight: bold;
					font-size: 32rpx;
					z-index: 1; // 层级设置
					white-space: nowrap; // 防止文字换行
				}

				.container-information-right {
					width: 140rpx;
					height: 60rpx;
					background-color: rgba(255, 69, 45, 1);
					border-radius: 30rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					z-index: 2; // 确保在文字上方

					&.followed-sticky {
						background-color: #ccc;

						.container-information-right-text {
							color: #fff;
							/* 已关注时文字颜色为白色 */
						}
					}

					.container-information-right-img {
						width: 28rpx;
						height: 28rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						margin-right: 10rpx;

						image {
							width: 28rpx;
							height: 28rpx;
							display: block;
						}
					}

					.container-information-right-text {
						font-size: 30rpx;
						color: rgba(255, 255, 255, 1);
						font-weight: bold;
						line-height: 1;
					}
				}
			}
		}

		.container-header {
			height: 440rpx;
			margin-bottom: -20rpx;

			.back-button {
				position: fixed;
				top: calc(var(--status-bar-height) + 30rpx);
				left: 30rpx;
				z-index: 10;
				width: 60rpx;
				height: 60rpx;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}

		.container-header {
			height: 440rpx;
			margin-bottom: -20rpx;

			.back-button {
				position: fixed;
				top: calc(var(--status-bar-height) + 30rpx);
				left: 30rpx;
				z-index: 10;
				width: 60rpx;
				height: 60rpx;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}

		.container-information {
			height: 140rpx;
			padding: 30rpx 30rpx 0;
			display: flex;
			justify-content: space-between;
			border-top-right-radius: 20rpx;
			border-top-left-radius: 20rpx;
			background-color: #ffffff;
			/* 添加背景色以显示圆角效果 */
			margin-top: -30rpx;
			/* 上移以覆盖轮播图底部，显示圆角 */
			position: relative;
			z-index: 9;
			/* 确保在轮播图上方 */

			.container-information-left {
				display: flex;

				.container-information-left-img {
					box-sizing: border-box;
					width: 140rpx;
					height: 140rpx;
					position: relative;
					border-radius: 24rpx;

					&::before {
						content: '';
						position: absolute;
						top: 0;
						left: 0;
						right: 0;
						bottom: 0;
						background: linear-gradient(to bottom right, rgba(255, 156, 112, 1), rgba(255, 197, 88, 1), rgba(255, 236, 112, 1));
						border-radius: 24rpx;
						z-index: -1;
					}

					&::after {
						content: '';
						position: absolute;
						top: 0;
						left: 0;
						right: 0;
						bottom: 0;
						background: #fff;
						border-radius: 24rpx;
						// 使用 inset 创建内部边框效果
						clip-path: inset(6rpx 6rpx 6rpx 6rpx round 18rpx);
						z-index: -1;
					}

					image {
						width: 120rpx;
						height: 120rpx;
						border-radius: 16rpx;
						position: absolute;
						top: 50%;
						left: 50%;
						transform: translate(-50%, -50%);
						z-index: 1;
					}
				}

				.container-information-left-content {
					margin-left: 40rpx;

					.container-information-left-content-top {
						display: flex;
						height: 70rpx;
						line-height: 70rpx;

						.container-information-left-content-top-name {
							font-size: 36rpx;
							font-weight: bold;
						}

						.container-information-left-content-top-brige {
							width: 40rpx;
							height: 40rpx;
							margin-left: 10rpx;

							image {
								margin-top: 15rpx;
								width: 40rpx;
								height: 40rpx;
							}
						}
					}

					.container-information-left-content-bottom {
						height: 70rpx;
						line-height: 70rpx;
						font-size: 26rpx;
						font-weight: 400;
					}

				}
			}

			.container-information-right {
				margin: 40rpx 0;
				width: 140rpx;
				height: 60rpx;
				border: 1px solid rgba(255, 69, 45, 1);
				border-radius: 30rpx;
				display: flex;
				align-items: center; // 垂直居中
				justify-content: center; // 水平居中

				&.followed {
					border: 1px solid #ccc;

					.container-information-right-text {
						color: #ccc;
					}
				}

				.container-information-right-img {
					width: 28rpx;
					height: 28rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-right: 10rpx; // 图标和文字之间的间距

					image {
						width: 28rpx;
						height: 28rpx;
						display: block;
					}
				}

				.container-information-right-text {
					font-size: 30rpx;
					color: rgba(255, 69, 45, 1);
					line-height: 1; // 确保文字垂直居中
				}
			}

		}

		.about {
			padding: 0 30rpx;
			margin-top: 30rpx;

			.about-title {
				font-weight: bold;
				font-size: 30rpx;
				line-height: 30rpx;
				margin-bottom: 30rpx;
			}

			.about-content-wrapper {
				position: relative;
			}

			.about-content {
				font-size: 28rpx;
				line-height: 42rpx;
				color: #333;
				text-align: justify;

				// 折叠状态：只显示四行
				&.collapsed {
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 4;
					overflow: hidden;
				}
			}

			.about-content-mask {
				position: absolute;
				bottom: 0;
				left: 0;
				right: 0;
				height: 120rpx;
				background: linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(255, 255, 255, 0.8), rgba(255, 255, 255, 1));
				// 仅保留蒙层效果，移除按钮
			}

			.action-btn-wrapper {
				display: flex;
				justify-content: center;
				padding: 20rpx 0 0;
			}

			// 展开按钮样式（在内容下方）
			.expand-btn {
				width: 120rpx;
				height: 50rpx;
				border-radius: 25rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 24rpx;
				color: rgba(255, 170, 13, 1);
				line-height: 24rpx;

				.expand-btn-img {
					width: 26rpx;
					height: 26rpx;
					border-radius: 50%;
					background-color: rgba(255, 170, 13, 1);
					position: relative;

					image {
						width: 14rpx;
						height: 14rpx;
						position: absolute;
						top: 50%;
						left: 50%;
						transform: translate(-50%, -50%);
					}
				}

				.expand-btn-text {
					padding-left: 10rpx;
				}
			}

			// 收起按钮样式
			.collapse-btn-content {
				width: 120rpx;
				height: 50rpx;
				border-radius: 25rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 24rpx;
				color: rgba(255, 170, 13, 1);
				line-height: 24rpx;

				.collapse-btn-text {
					padding-left: 10rpx;
				}

				.collapse-btn-img {
					width: 26rpx;
					height: 26rpx;
					border-radius: 50%;
					background-color: rgba(255, 170, 13, 1);
					position: relative;

					image {
						width: 14rpx;
						height: 14rpx;
						position: absolute;
						top: 50%;
						left: 50%;
						transform: translate(-50%, -50%);
					}
				}
			}
		}

		.TalentShow {
			padding: 30rpx 30rpx 20rpx;

			.TalentShow-title {
				font-weight: bold;
				font-size: 30rpx;
				line-height: 30rpx;
				position: relative;
				display: inline-block;

				.title-text {
					position: relative;
					z-index: 2; // 确保文字在图片上方
				}

				.TalentShow-img {
					position: absolute;
					top: 70%;
					left: 0;
					transform: translateY(-50%);
					width: 100%;
					height: 26rpx;
					z-index: 1; // 图片在文字下方

					image {
						width: 100%;
						height: 26rpx;
						display: block;
					}
				}
			}
		}

		.waterfall-section {
			padding: 0 10rpx;
			padding-bottom: 130rpx;
		}
	}
</style>